#include "texture.h"

TextureMgr* TextureMgr::mTexMgr = NULL;

TextureMgr* TextureMgr::Instance()
{
	if ( !mTexMgr ) {
		mTexMgr = new TextureMgr;
	}
	return mTexMgr;
}

TextureMgr::~TextureMgr()
{
	mTexMgr = NULL;
}

Texture* TextureMgr::GetTexture( string key )
{
	if ( mTexs.find( key ) != mTexs.end() ) {
		return mTexs[ key ];
	}
	return NULL;
}

Texture* TextureMgr::CreateTexture( String filename, string key )
{
	if ( mTexs.find( key ) != mTexs.end() ) {
		return mTexs[ key ];
	}

	Texture* tex = new Texture();
	LPDIRECT3DTEXTURE9 pTex;
	HR( D3DXCreateTextureFromFile( RenderFrame::GetD3DDevice(), filename, &pTex ) );

	tex->SetTexture( pTex );
	mTexs.insert( make_pair( key, tex ) );
	return tex;
}

Texture* TextureMgr::CreateTextureEX( String filename, string key )
{
	if ( mTexs.find( key ) != mTexs.end() ) {
		return mTexs[ key ];
	}

	Texture* tex = new Texture();
	LPDIRECT3DTEXTURE9 pTex;
	D3DXIMAGE_INFO imgInfo;
	HR( D3DXCreateTextureFromFileEx( RenderFrame::GetD3DDevice(),
									 filename, 
									 D3DX_DEFAULT_NONPOW2, 
									 D3DX_DEFAULT_NONPOW2,
									 D3DX_DEFAULT,
									 D3DUSAGE_DYNAMIC,
									 D3DFMT_A8R8G8B8,
									 D3DPOOL_DEFAULT,
									 D3DX_DEFAULT,
									 D3DX_DEFAULT,
									 0,
									 &imgInfo, 
									 NULL,
									 &pTex ) );
	
	tex->SetTexture( pTex );
	tex->SetWidth( imgInfo.Width );
	tex->SetHeight( imgInfo.Height );

	mTexs.insert( make_pair( key, tex ) );
	return tex;
}

void TextureMgr::ReleaseTextures()
{
	auto itr = mTexs.begin();
	while( itr != mTexs.end() ) {
		SAFE_RELEASE( itr->second );
		++itr;
	}
}
